package org.demo.es.service.impl;

import co.elastic.clients.elasticsearch.core.search.Hit;
import org.demo.es.service.ElasticSearchIndexService;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.ElasticsearchException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * ElasticSearchService实现类
 * @author moxiaoli
 */
@Service
@Slf4j
public class ElasticSearchIndexServiceImpl implements ElasticSearchIndexService {

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @Override
    public boolean createIndex(String index) {
        try {
            elasticsearchClient.indices().create(r -> r.index(index));
            return true;
        }catch (IOException | ElasticsearchException e){
            log.error("索引创建失败：{}", e.getMessage());
        }
        return false;
    }

    @Override
    public boolean deleteIndex(String index) {
        try {
            elasticsearchClient.indices().delete(r -> r.index(index));
            return true;
        }catch (IOException e){
            log.error("索引删除失败：{}", e.getMessage());
        }
        return false;
    }

    @Override
    public boolean isIndexExist(String index) {
        try {
            return elasticsearchClient.indices().exists(r -> r.index(index)).value();
        }catch (IOException e){
            log.error("索引查询失败：{}", e.getMessage());
        }
        return false;
    }

    @Override
    public List<String> getAllIndex() {
        try {
            return new ArrayList<>(elasticsearchClient.indices().get(r -> r.index("*")).result().keySet());
//            return elasticsearchClient.indices().get(r -> r.index("*")).result().keySet().stream().collect(Collectors.toList());
        }catch (IOException e){
            log.error("索引查询失败：{}", e.getMessage());
        }
        return null;
    }

    @Override
    public List<Map> getAllDocument() {
        try {
            return elasticsearchClient.search(s -> s
//                    .query(q->q.matchAll(b -> b))
                    .withJson(new StringReader(
                            "{" +
                                    "  \"query\": {" +
                                    "    \"match_all\": {}" +
                                    "  }" +
                                    "}"
                    ))
                    , Map.class
            ).hits().hits().stream().map(Hit::source).collect(java.util.stream.Collectors.toList());
        } catch (Exception e) {
            log.error("索引查询失败：{}", e.getMessage());
        }
        // 返回一个空的列表，而不是null
        return Collections.emptyList();
    }

}
